const { literal, Op, Sequelize } = require("sequelize");
const { User } = require('../models/index')

users =function(){}

users.regist = async (req, res, next) => {
	const { username, password } = req.body
	User.create({ username, password }).then((result)=>{
    	console.log('注册成功')
		  res.redirect('/login')
	}).catch((error)=>{
      console.log('注册失败')
		  res.redirect('/regist') 
    })  
};

users.login=function(ws,req){
  console.log('连接成功')
  ws.on('message', function (msg) {
    data = JSON.parse(msg)
    //console.log(msg)
    User.findOne({where:data,raw:true}).then((result)=>{
      if(result){
        console.log(result)
        ws.send('登录成功')
      }
      else ws.send('登录失败')
    }).catch((error)=>{
      console.log(error)
    })    
  })
  ws.send('连接成功')  
  //req.body为{}
}

users.logon = (ws,req) => {
    console.log('连接成功')
    ws.on('message', function (reqdata) {
      if(!reqdata)return;
      data = JSON.parse(reqdata)     
      User.findOne({where:data.data,raw:true}).then((result)=>{
        if(result){
          console.log(result)
          ws.send(JSON.stringify({code:data.code,info:{status:201,msg:'登录成功'},data:{id:result.id,name:result.name,role:''}}))
        }
        else ws.send(JSON.stringify({code:data.code,info:{status:301,msg:'登录失败'},data:{}}))
      }).catch((error)=>{
        ws.send(JSON.stringify({code:data.code,info:{status:301,msg:'登录失误'},data:{}}))
        console.log(error)
      })   
    })
    ws.on('close',function(){
      console.log('连接关闭')
    })
}
users.regist2 = (ws, req) => {
    ws.on('message', function (msg) {
      if(!msg)return;
      data = JSON.parse(msg)
      //console.log(data)
      User.create(data).then((result)=>{
        if(!result)return;
        if(result){
          console.log(result.dataValues)
          backdata = {code:data.code,info:{status:201,msg:result.name+'注册成功'},data:{}}
          ws.send(JSON.stringify(backdata))
        }
      }).catch((error)=>{
        ws.send(JSON.stringify({code:data.code,info:{status:301,msg:'注册失败'},data:{}}))
        console.log(error)
      })   
    })  
}

module.exports = users;
